package com.vnp.vchat;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.vchat.Util.PreferenceHelper;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoginWithGoogleMainActivity extends Activity {
	
	WebView webviewLoginFB;
	ProgressBar progressBar;
	String urllogin = "http://vchat.vn/service/svlogin1.php?provider=gg";
	PreferenceHelper preferenceHelper;
	String access = "http://vchat.vn/service/svlogin1.php?access_code=";
	boolean isLoaded= false;
	
	ImageButton btnBack;
	TextView title;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_with_google_main);
		
		preferenceHelper = new PreferenceHelper(this);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		title = (TextView) findViewById(R.id.title);
		btnBack.setVisibility(View.VISIBLE);

		webviewLoginFB= (WebView) findViewById(R.id.web);
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
		progressBar.setVisibility(ProgressBar.GONE);
		
		webviewLoginFB.getSettings().setJavaScriptEnabled(true);
		webviewLoginFB.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
                if (progress == 100) {
                	progressBar.setVisibility(ProgressBar.INVISIBLE);
                    progressBar.setProgress(0);
                } else {
                	progressBar.setVisibility(ProgressBar.VISIBLE);
                }
            }
        });
		

		webviewLoginFB.setWebViewClient(new MyWebViewClient());
		webviewLoginFB.loadUrl(urllogin);
		
		init();
	}
	
	
	private void init(){
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		title.setText("Đăng nhập");
	}
	
	private class MyWebViewClient extends WebViewClient {
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, final String url) {
	    	if(url.startsWith(access)&&(isLoaded == false)){
				Log.i("DATA", url);
				isLoaded = true;
			       if (url.startsWith(access)) {
			    	   webviewLoginFB.setVisibility(View.GONE);
						Thread tr = new Thread(){

							@Override
							public void run() {
								String str = "";
						        HttpResponse response;
						        HttpClient myClient = new DefaultHttpClient();
						        HttpPost myConnection = new HttpPost(url);
						         Log.i("DATA", "--------------1");
						        try {
						            response = myClient.execute(myConnection);
						            Log.i("DATA", "--------------2");
						            str = EntityUtils.toString(response.getEntity(), "UTF-8");
						            Log.i("DATA", "DATA CHUA PASER: "+str);
						        } catch (ClientProtocolException e) {
						            e.printStackTrace();
						        } catch (IOException e) {
						            e.printStackTrace();
						        }
						        

			             try{
			            	 JSONObject jo = new JSONObject(str);
					            
					            int status = jo.getInt("status");
					            if (status == 1){
					            	
					            	JSONObject uinf = jo.getJSONObject("uinfo");
					            	JSONObject settings = jo.getJSONObject("setting");
					            	
					            	preferenceHelper.setUserId(uinf.getString("use_sso_id"));
					            	preferenceHelper.setHash(jo.getString("hash"));
					            	preferenceHelper.setDomainConnect(jo.getString("domain_connect"));
					            	preferenceHelper.setPostConnect(jo.getString("port_connect"));
					            	preferenceHelper.setDataJoin(jo.getString("datajoin"));
					            	preferenceHelper.setSettingNotifi(settings.getString("notifi"));
					            	preferenceHelper.setSettingFeed(settings.getString("feed"));
					            	preferenceHelper.setSettingDisplay(settings.getString("showmsg"));
					            	preferenceHelper.setUserName(uinf.getString("use_name"));
					            	preferenceHelper.setMyAvatar(uinf.getString("use_avatar"));
					            	gotoMain();
					            	
					            } else if (status == 0) {
					            	reloadLogin();
					            }
					            
					             
					        } catch ( JSONException e) {
					        	Intent loginIntent = new Intent(LoginWithGoogleMainActivity.this, LoginWithGoogleMainActivity.class);
				            	finish();
				                loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				                startActivity(loginIntent);
					            e.printStackTrace();                
					        }
							}
							
						};
						tr.start();

					}
			} else {
				webviewLoginFB.loadUrl(url);
			}
	        return true;
	    }
	    
	    


		@Override
		public void onPageStarted(WebView view, final String url, Bitmap favicon) {
			
		}
	    
	}
	
	void gotoMain(){
		Intent t = new Intent(LoginWithGoogleMainActivity.this, MainActivity.class);
		finish();
		/** on your logout method:**/
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("com.package.FINISH");
		sendBroadcast(broadcastIntent);
		startActivity(t);
	}
	
	void reloadLogin(){
		Intent loginIntent = new Intent(LoginWithGoogleMainActivity.this, LoginWithGoogleMainActivity.class);
    	finish();
        loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(loginIntent);
	}
}
